import Utils from '@/utils/index'
import { View, Text, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Dialog, ImageViewer, Tag } from 'antd-mobile'
import { useState, useEffect, useMemo } from 'react'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '@/pages/components/utils';
import FileItem from '../myComponent/fileItem'
import Header from '../myComponent/header'
import { useDocumentTitle, useGetFileName, useGetImgInRichText, useGetIsMapArray, useGetOutsideUrl, useResetDate, useTitleCut } from '@/utils/myUtils'
import PopoverDownload from '../myComponent/popoverDownload'
import { useSelector, useDispatch } from 'react-redux'
import LgButton from '../components/button'
import { setIdentityCode, setSysInfo, setToken, setType, setUserInfo } from '@/store/slice'
import { Current } from '@tarojs/runtime'
import { HttpDelete, HttpGet, HttpPut, HttpPost } from '@/network/servers'
import { getBaseUrl, requestSystemUrl } from '@/network/baseUrl'
import Loading from '@/myComponent/load'
import LgInput from '@/pages/components/input'
import LgCell from '@/pages/components/cell'
import { LgPopLayer } from '@/pages/components/popLayerDefault'
import LgCheckbox from '@/pages/components/checkbox'
import LgSwitch from '@/pages/components/switch'
import MyEditor from './MyEditor'
import LancooSelect from '@/pages/LGcomponents/LgSelectModalEdu'
import LgEmptyContent from '../components/emptyContent'
import Proxy from '@/network/proxy'
import Detail from '../detail/index'


import './index.scss'
const browserController = getBrowserController()
const net = getNet()
const storage = getStorage()
var wx = require('weixin-js-sdk')

const requireContext = require.context("../images/fileIcon", true, /^\.\/.*\.svg$/);
const svgs = requireContext.keys().map(requireContext);
const keys = requireContext.keys()
let fileObj = {}

keys.map((item, index) => {
    let str = item.replace('./', "").replace('.svg', "")
    fileObj[str] = svgs[index]
})

function App() {

    const dispatch = useDispatch()
    const commonData = useSelector((state: any) => state.commonData)

    const {
        userInfo,
        type,
        token,
        lg_ic,
        sysInfo,
    } = commonData

    useDocumentTitle('发布公告', false)

    const [detail, setDetail] = useState<any>({})
    const [seat, setSeat] = useState<any>()
    const [imgList, setImgList] = useState([])
    const [fileList, setFileList] = useState([])
    const [myTypeList, setMyTypeList] = useState<any>([])
    const [depList, setDepList] = useState<any>([])
    const [richTextImg, setRichTextImg] = useState<any>([])
    const [visible, setVisible] = useState(false)
    const [currentFile, setCurrentFile] = useState<any>({})
    const [currentIndex, setCurrentIndex] = useState<any>()
    const [title, setTitle] = useState<any>('')
    const [typeName, setTypeName] = useState<any>('')
    const [typeVisible, setTypeVisible] = useState(false)
    const [depVisible, setDepVisible] = useState(false)
    const [advancedVisible, setAdvancedVisible] = useState(false)
    const [isTop, setIsTop] = useState<boolean>(false)
    const [userVisible, setUserVisible] = useState<boolean>(false)
    const [equipVisible, setEquipVisible] = useState<boolean>(false)
    const [content, setContent] = useState<any>('')
    const [typeItem, setTypeItem] = useState<any>(null)
    const [depItem, setDepItem] = useState<any>(null)
    const [canViewList, setCanViewList] = useState<any>([])
    const [selectUserList, setSelectUserList] = useState<any>([])
    const [allSelectObj, setAllSelectObj] = useState<any>([])
    const [selectEquipList, setSelectEquipList] = useState<any>([])
    const [chooseDeviceList, setChooseDeviceList] = useState<any>([])
    const [selectDeviceList, setSelectDeviceList] = useState<any>([])
    const [classList, setClassList] = useState<any>([])
    const [buildList, setBuildList] = useState<any>([])
    const [boardList, setBoardList] = useState<any>([])
    const [officePlatform, setOfficePlatform] = useState<any>({})
    const [showClassList, setShowClassList] = useState<boolean>(false)
    const [showBuildList, setShowBuildList] = useState<boolean>(false)
    const [showBoardList, setShowBoardList] = useState<boolean>(false)
    const [init, setInit] = useState<boolean>(false)
    const [preview, setPreview] = useState<boolean>(false)
    const [previewData, setPreviewData] = useState<any>({})
    const [group, setGroup] = useState([])
    const [sensetiveData, setSensetiveData] = useState([])

    // const group = [
    //     { label: '管理员', value: 6, checked: false },
    //     { label: '领导', value: 8, checked: false }
    // ]

    const showFile = (item, e?) => {
        e && e.stopPropagation()
        browserController.openFileReader(storage.get(`bulletin_${item.attachmentId}`))
    }

    // 获取身份列表
    const getIdentityList = (eduId) => {
        let url = 'api/common/user/type',
            data = {
                eduId,
                // userType: '6,8'
            }
        HttpGet({
            url,
            data,
            load: true
        }).then((result) => {
            let data = result;
            let tempData = []
            data.forEach(i => {
                tempData.push({ label: i.userTypeName, value: i.identityCode, checked: false })
            })
            setGroup(tempData)

            // setIdentityList(data);
        })
    }

    const download = async (item, index, type) => {
        setVisible(false)
        console.log(item, '*******', index, type)
        let fileName = useGetFileName(item.name)
        let url = item.url
        if (item?.preView || storage.get(`bulletin_${item.attachmentId}`)) { //当前文件已下载，直接预览
            showFile(item)
            return
        }

        if (Utils.getSystemInfo() === 'weapp') {
            const params = await getWxSDKParams([])
            wx.config(params);
            try {
                browserController.openFileForWebview(wx, { fileUrl: url, fileName: fileName })
            } catch (error) {
                Taro.showToast({ title: error, icon: 'none' })
            }
        } else {
            let arr: any = fileList.concat([])
            net.downloadFile({
                url,
                fileName: item.name,
                onProgress: process => {
                    Taro.showToast({
                        icon: 'loading',
                        title: `正在下载${process}%`
                    })
                },
                onSuccess: path => {
                    if (type === 'download') {
                        Taro.showToast({
                            title: '下载成功',
                            icon: 'success',
                            duration: 2000
                        })
                    }
                    arr[index].preView = true
                    storage.set(`bulletin_${item.attachmentId}`, path)
                    setFileList(arr)
                    if (type === 'preview') {
                        browserController.openFileReader(path)  //下载完就预览
                    }
                },
                onError: error => {
                    Taro.showToast({
                        title: '下载失败',
                        icon: 'none',
                        duration: 2000
                    })
                }
            })
        }
    }

    const showPreView = (item) => {
        let arr: any = []
        imgList.map((t: any) => {
            arr.push(t.url)
        })
        ImageViewer.Multi.show({ images: arr, maxZoom: 10 })
    }

    const getData = (bulletinId, typeList) => {
        let url = '/api/bulletin/info/edit/detail', body = { bulletinId }
        if (!bulletinId) return;
        HttpGet({
            url,
            data: body,
            load: true
        }).then((result) => {
            setDetail(result)
            setTitle(result.title);
            let selectTypeIndex = 0;
            typeList.forEach((item, index) => {
                if (item.typeId === result.typeId) {
                    selectTypeIndex = index;
                }
            })
            changeObj(typeList[selectTypeIndex], 'type');
            setContent(result.content);
            setIsTop(result.seat == '0' ? false : true)
            //需要将选择对象还原成可识别的数组
            let receiveInfo = result.receiver ? result.receiver : {};
            let list: any = [], deviceList: any = [];
            for (let key in receiveInfo) {
                if (!Array.isArray(receiveInfo[key])) {
                    return;
                }
                if (key === "persons") {
                    receiveInfo[key].forEach((item) => {
                        list.push({
                            ...item,
                            id: item.userId,
                            name: item.userName,
                            type: "user",
                            floorNum: 6,
                            groupType: item.userType == 1 ? "tea" : item.userType == 2 ? "stu" : item.userType == 3 ? "parent" : "admin"
                        })
                    })
                }
                if (key === "grades") {
                    receiveInfo[key].forEach((item) => {
                        list.push({
                            ...item,
                            id: item.gradeId,
                            name: item.gradeName
                        })
                    })
                }
                if (key === "classes") {
                    receiveInfo[key].forEach((item) => {
                        list.push({
                            ...item,
                            id: item.classId,
                            name: item.className
                        })
                    })
                }
                if (key === "students") {
                    receiveInfo[key].forEach((item) => {
                        list.push({
                            ...item,
                            id: item.classId || item.gradeId || item.majorId || item.collegeId,
                            name: item.className || item.gradeName || item.majorName || item.collegeName,
                            floorNum: item.classId ? 5 : item.gradeId ? 4 : item.majorId ? 3 : 2,
                            type: item.classId ? "class" : item.gradeId ? "grade" : item.majorId ? "major" : "college",
                            groupType: "stu"
                        })
                    })
                }
                if (key === "parents") {
                    receiveInfo[key].forEach((item) => {
                        list.push({
                            ...item,
                            id: item.classId || item.gradeId || item.majorId || item.collegeId,
                            name: item.className || item.gradeName || item.majorName || item.collegeName,
                            floorNum: item.classId ? 5 : item.gradeId ? 4 : item.majorId ? 3 : 2,
                            type: item.classId ? "class" : item.gradeId ? "grade" : item.majorId ? "major" : "college",
                            groupType: "parent"
                        })
                    })
                }
                if (key === "teachers") {
                    receiveInfo[key].forEach((item) => {
                        list.push({
                            ...item,
                            id: item.subjectId || item.groupId || item.collegeId,
                            name: item.subjectName || item.groupName || item.collegeName,
                            floorNum: item.subjectId || item.groupId ? 3 : 2,
                            type: item.subjectId || item.groupId ? "group" : "college",
                            groupType: "tea"
                        })
                    })
                }
                if (key === "identities") {
                    receiveInfo[key].forEach((item) => {
                        list.push({
                            ...item,
                            id: item.identityCode,
                            name: item.identityName,
                            floorNum: 2,
                            type: "identity",
                            groupType: "admin"
                        })
                    })
                }
                if (key === "departments") {
                    receiveInfo[key].forEach((item) => {
                        list.push({
                            ...item,
                            id: item.departmentId,
                            name: item.departmentName,
                            type: "org",
                            groupType: "org"
                        })
                    })
                }
                setSelectUserList(list);
                if (key === "devices") {  //如何转过来的就要转回去才能识别
                    receiveInfo[key].forEach((item) => {
                        if (item.deviceType == 1) {  //班牌
                            deviceList.push({
                                boardId: item.deviceId,
                                boardName: item.deviceName,
                            })
                        } else if (item.deviceType == 2) {  //楼牌
                            deviceList.push({
                                buildingBoardId: item.deviceId,
                                buildingBoardName: item.deviceName
                            })
                        } else {
                            deviceList.push({
                                buildingId: item.deviceId,
                                buildingName: item.deviceName
                            })
                        }
                    })
                }
            }
            // console.log(deviceList,'deviceList');
            let depItem: any = {};
            depItem.departmentId = result.departmentId;
            depItem.departmentName = result.departmentName;
            setDepItem(depItem);

            setChooseDeviceList(deviceList);
            let attachments = result.attachmentList || result.attachments
            if (useGetIsMapArray(attachments)) {
                let imgArr = [] as any, fileArr = [] as any
                attachments.map(item => {
                    let fileType = Utils.getFileType(item.name)
                    item.fileName = item.name;
                    item.url = useGetOutsideUrl(item.url, '/upload/', getBaseUrl())
                    if (fileType == 'img') {
                        imgArr.push(item)
                    } else {
                        fileArr.push(item)
                    }
                })

                // console.log(fileArr,imgArr)
                let richImgs = useGetImgInRichText(result.content)

                setRichTextImg(richImgs)
                setFileList(fileArr)
                setImgList(imgArr)
            }
        })
    }

    const getCommonData = async (params) => {
        setInit(false);
        HttpGet({ //用户信息
            url: params.baseUrl + '/api/common/user',
            data: {
                token: params.lg_tk || token,
            }
        }).then((userInfo) => {
            dispatch(setUserInfo(userInfo))
            HttpGet({ //学校信息
                url: params.baseUrl + '/api/common/system/info',
                data: {
                    eduId: userInfo.eduId,
                    token: params.lg_tk
                }
            }).then(async (sysInfo) => {
                console.log(sysInfo)
                dispatch(setSysInfo(sysInfo))
                await getOfficePlatform();
                await getReleaseDep(sysInfo);
                await getMyTypeList(userInfo);
                await getIdentityList(userInfo.eduId)
            })
        })
    }

    const initWxSdk = async () => {
        const params = getWxSDKParams(['previewImage', 'getLocation'])
        wx.config(params);
        wx.ready(function () {
            // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
            console.log('ready')
        });
        wx.error(function (res) {
            // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
            console.log(res)
        });
    }

    useEffect(() => {
        let top = Current.router?.params.top
        setSeat(top)
        if (Utils.getSystemInfo() === 'weapp') {
            initWxSdk()
        }
        // 直接跳转当前详情页 需要初始化数据获取
        dispatch(setType(Utils.getQueryVariable('type')))
        let params = {
            lg_tk: Utils.getQueryVariable('lg_tk') || storage.get('token'),
            lg_ic: Utils.getQueryVariable('lg_ic') || storage.get('lg_ic'),
            baseUrl: getBaseUrl()
        }

        dispatch(setToken(params.lg_tk))
        dispatch(setIdentityCode(params.lg_ic))

        if (Utils.getSystemInfo() === 'weapp') {
            requestSystemUrl('220').then((baseUrl) => {
                params = Object.assign({}, params, { baseUrl })
                window.baseUrl = baseUrl
                getCommonData(params)
            })
        } else {
            getCommonData(params)
        }

    }, [])

    // 获取类型负责类型列表
    const getMyTypeList = (userInfo) => {
        console.log(userInfo)
        let url = '/api/bulletin/director/type',
            body = {
                eduId: userInfo.eduId,
                directorId: userInfo.userId,
                identityCode: userInfo.identityCode || Utils.getQueryVariable('lg_ic') || storage.get('lg_ic'),
            }
        HttpGet({
            url,
            data: body
        }).then((typeList) => {
            setMyTypeList(typeList);
            if (useGetIsMapArray(typeList)) {
                // changeObj(typeList[0], 'type');
            }
            let bulletinId = Current.router?.params.bulletinId
            if (bulletinId) {
                getData(bulletinId, typeList);
            }
        })
    }

    // 发布部门(第一级)
    const getReleaseDep = (schoolInfo) => {
        let url = '/api/constant/chief/departmentTree',
            body = {
                // sysId: schoolInfo.sysId,
                eduId: userInfo.eduId,
                // departmentId: ''
            }
        HttpGet({
            url,
            data: body,
            header: {
                'Authorization': Utils.getQueryVariable('lg_tk')
            }
        }).then((depList) => {
            console.log(depList)
            setDepList(depList.departmentInfoVoList);
            setTimeout(() => {
                setInit(true);
            }, 300);
        })
    }

    //打开弹窗
    const handlePopLayer = (type, flag) => {
        if (type === 'open') {
            //打开弹出层时阻止页面滑动
            document.body.style.overflow = 'hidden';

            switch (flag) {
                case 'type': setTypeVisible(true);
                    break;
                case 'dep': setDepVisible(true);
                    break;
                case 'advanced': setAdvancedVisible(!advancedVisible);
                    break;
                case 'user': setUserVisible(true);
                    break;
                case 'equip': setEquipVisible(true), showSelectDevice(1);
                    break;
                case 'build': setShowBuildList(!showBuildList);
                    break;
                case 'class': setShowClassList(!showClassList);
                    break;
                case 'board': setShowBoardList(!showBoardList);
                    break;
                default: '';
                    break;
            }

        } else {
            document.body.style.overflow = '';

            switch (flag) {
                case 'type': setTypeVisible(false);
                    break;
                case 'dep': setDepVisible(false);
                    break;
                default: '';
                    break;
            }

        }
    }

    // 设备选择
    const showSelectDevice = (type) => {
        //type : 1是选择， 0是重选
        //获取班牌、楼牌、广播终端
        if (type === 0) {
            //重选时需要把之前存储的已选设备清空
            setChooseDeviceList([]);
            setSelectDeviceList([]);
            return;
        }
        let url = 'api/commons/device/class/boards';
        HttpGet({
            url,
            data: {}
        }).then((deviceList) => {
            setClassList(deviceList);
        })

        HttpGet({
            url: 'api/commons/device/building/boards',
            data: {}
        }).then((boardsList) => {
            let terminalTypes = [...new Set(boardsList.map(item => item.buildingBoardType))];
            let classifiedData = terminalTypes.map(type => {
                return {
                    "buildingBoardId": type,
                    "buildingBoardName": getBuildingBoardName(type)
                };
            });
            function getBuildingBoardName(type) {
                switch (type) {
                    case '1':
                        return "楼牌";
                    case '2':
                        return "校牌";
                    case '3':
                        return "互动牌";
                    default:
                        return "未知类型";
                }
            }
            setBuildList(classifiedData);
            // let updateList: any = [];
            // boardsList.forEach((item) => {
            //     updateList.push({
            //         buildingBoardId: item.buildingBoardId,
            //         buildingBoardName: item.buildingBoardName
            //     })
            // })
            // setBuildList(updateList);
        })

        HttpGet({
            url: 'api/commons/device/radio/broadcasts',
            data: {
                userId: userInfo.userId,
                token
            }
        }).then((broadcasts) => {
            setBoardList(broadcasts);
        })

        if (type === 1) {
            setSelectEquipList(chooseDeviceList);
        }

    }

    const changeObj = (obj, type) => {
        console.log(obj)
        console.log(type)
        if (type === 'type') {
            setTypeItem(obj);
            setTypeVisible(false);
            let group1: any = [];
            console.log(group)
            if (obj.scope.length > 0) {
                group.forEach(item => {
                    item.checked = false;
                    obj.scope.forEach(itm => {
                        if (item.value == itm) {
                            item.checked = true;
                            group1.push(item)
                        }
                    })
                })
            }
            setCanViewList(group1);
        } else if (type === 'dep') {
            setDepItem(obj);
            setDepVisible(false);
        }
    }

    // 勾选可查看对象
    const changeChecked = (index) => {
        let checked = canViewList[index].checked;
        let newData = [...canViewList];
        canViewList[index].checked = !checked;
        setCanViewList(newData);
    }

    // 选择设备
    const changeCheckedEquip = (item) => {
        const index = selectEquipList.findIndex(
            (equip) =>
                (equip.boardId && equip.boardId === item.boardId) ||
                (equip.buildingId && equip.buildingId === item.buildingId) ||
                (equip.buildingBoardId && equip.buildingBoardId === item.buildingBoardId)
        );

        if (index !== -1) {
            // 如果存在，从 selectEquipList 中移除该项
            const newList = [...selectEquipList];
            newList.splice(index, 1);
            setSelectEquipList(newList);
        } else {
            // 如果不存在，将该项添加到 selectEquipList 中
            setSelectEquipList((prevList) => [...prevList, item]);
        }
    };

    // 置顶
    const setTop = () => {
        setIsTop(!isTop);
    }

    const confirm = (data) => {
        if (!useGetIsMapArray(data)) {
            return
        }
        setSelectUserList(data);
        setUserVisible(false);
    }

    const goBack = () => {
        if (preview) {
            setPreview(false);
        } else if (userVisible || equipVisible) {
            setUserVisible(false);
            setEquipVisible(false);
            setSelectEquipList([]);
        } else {
            Taro.navigateBack({
                delta: 1
            })
        }
    }

    //上传文件
    const uploadSuccess = (res) => {
        let url = sysInfo.itemUrl + `api/commons/file/batch/upload`
        if (Utils.getSystemInfo() == 'weapp') {
            url = Proxy.transmitUrlToVisit(url)
        }
        let fileArr: any = fileList.concat([])
        let imgArr: any = imgList.concat([])

        if ((fileArr.length + imgArr.length) > 4) {
            Taro.showToast({
                title: '只能上传5个文件!',
                icon: 'none',
                duration: 2000
            })
            return;
        }
        const tempFilePaths = res.tempFiles
        let formData = new FormData();
        formData.append('files', tempFilePaths[0].originalFileObj);
        formData.append('modelName', 'noticeCenter');
        const xhr = new XMLHttpRequest();
        xhr.open('POST', url);
        xhr.setRequestHeader('Authorization', token);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    const result = JSON.parse(xhr.responseText);
                    const data = result.data[0]
                    if (result.code == '200') {
                        Taro.showToast({
                            title: '上传成功'
                        })
                        if (data.type == 'image') {
                            imgArr.push(data)
                            setImgList(imgArr)
                        } else {
                            fileArr.push(data)
                            setFileList(fileArr)
                        }
                    }
                } else {
                    Taro.hideLoading()
                    setTimeout(() => {
                        Taro.showToast({
                            title: '上传失败',
                            icon: 'none'
                        })
                    }, 500);
                }
            }
        };
        xhr.upload.onprogress = function (e) {
            if (e.lengthComputable) {
                const percent = Math.round((e.loaded / e.total) * 100);
                Taro.showToast({
                    icon: 'loading',
                    title: `上传中${percent}%`,
                    mask: true,
                    duration: 10000
                })
            }
        };
        xhr.send(formData);
    }

    // 上传文件失败
    const uploadFail = () => {
        Taro.showToast({
            title: '上传失败请联系管理员',
            icon: 'none'
        })
    }

    //发布/保存公告
    const releaseNotice = async (type, sensitiveContent = "") => {
        try {
            if (!title) {
                await Taro.showToast({
                    title: '请输入公告标题!',
                    icon: 'none',
                    duration: 2000,
                })
                return;
            }
        } catch (error) {
            console.error(error);
        }

        if (!typeItem) {
            Taro.showToast({
                title: '请选择公告类型',
                icon: 'none',
                duration: 2000,
            })
            return;
        }

        if (!depItem) {
            Taro.showToast({
                title: '请选择发布部门！',
                icon: 'none',
                duration: 2000,
            })
            return;
        }

        if (!content || isStringEmpty(content)) {
            Taro.showToast({
                title: '请输入公告内容！',
                icon: 'none',
                duration: 2000,
            })
            return;
        }

        let attachmentsList: any = fileList.concat(imgList);

        if (attachmentsList.length > 0) {
            attachmentsList.forEach((item, index) => {
                item.orderNum = index
                item.name = item.fileName
                switch (item.type) {
                    case "document": item.type = '1';
                        break;
                    case "image": item.type = '2';
                        break;
                    case "audio": item.type = '3';
                        break;
                    case "video": item.type = '4';
                        break;
                    case "pack": item.type = '6';
                        break;
                    default: item.type = '5';
                        break
                }

            })
            console.log('attachmentsList', attachmentsList);
        }

        let receiver: any = {};
        if (selectEquipList) {
            let devicesArr = selectEquipList
            devicesArr.forEach(item => {
                if (item.boardId) {//班牌
                    item.deviceType = '1';
                } else if (item.buildingBoardId) {//楼牌
                    item.deviceType = '2';
                } else {
                    item.deviceType = '3';
                }
                item.deviceId = item.boardId || item.buildingId || item.buildingBoardId;
                item.deviceName = item.boardName || item.buildingName || item.buildingBoardName;
            })
            receiver.devices = devicesArr
            receiver.grades = []
            receiver.classes = []
            receiver.allList = []
        }
        receiver.persons = selectUserList;

        console.log('receiver', receiver);
        let identityCode = lg_ic, identityInfos = userInfo.identityList;
        let identityName;
        for (let i = 0; i < identityInfos.length; i++) {
            if (identityInfos[i].identityCode === identityCode) {
                identityName = identityInfos[i].identityName;
                break;
            }
        }
        // console.log(identityCode, 'identityCode', identityName);

        // return;
        let url = ''
        if (type === 'release') {
            url = 'api/bulletin/created/release' // 发布
        } else {
            url = 'api/bulletin/created/save'  //保存
        }

        let scopeArr: any = []
        canViewList.forEach(item => {
            if (item.checked === true) {
                if (item.value === 0) {
                    scopeArr.push(0, 6, 7, 8);
                } else {
                    scopeArr.push(item.value);
                }
            }
        })
        if (scopeArr.length == 0) {
            Taro.showToast({
                title: '可查看对象不可为空',
                icon: 'none',
                duration: 2000,
            })
            return;
        }
        Taro.showLoading({
            title: '请稍等~'
        })
        console.log(sysInfo)
        console.log(userInfo)
        let data = {
            bulletinId: detail && detail.bulletinId,
            title: title,
            content: sensitiveContent ? sensitiveContent : content,
            typeId: typeItem.typeId,
            departmentId: depItem.departmentId,
            departmentName: depItem.departmentName,
            userId: userInfo.userId,
            userName: userInfo.userName,
            seat: isTop ? '1' : '0',
            pushOfficialWebsite: '0',
            sysId: sysInfo.sysId,
            way: Utils.getSystemInfo() === 'weapp' ? 3 : 2,
            eduId: userInfo.eduId,
            eduName: userInfo.eduName,
            eduType: sysInfo.productType,
            attachments: attachmentsList,
            receiver,
            identityCode: userInfo.identityCode,
            identityName: userInfo.identityName,
            scope: scopeArr,
        }
        if (type === 'preview') {
            setPreviewData(data);
            setPreview(true);
            Taro.hideLoading();
            return;
        }
        console.log(data, 'data');

        HttpPost({
            url,
            data,
            header: {
                Authorization: token
            }
        }).then((result) => {
            Taro.hideLoading();
            // Taro.redirectTo({
            //     url: '/pages/index/index'
            // })
            Taro.navigateTo({
                url: `/pages/index/index?lg_tk=${token}&type=admin`
            })
            setTimeout(() => {
                Taro.showToast({
                    title: type === 'release' ? '发布成功' : ' 保存成功'
                })
            }, 1000);
        })
    }

    //检测是否全为空格
    const isStringEmpty = (str) => {
        // 去除 HTML 标签
        var content = str.replace(/<(.*?)>/g, '');

        // 将 &nbsp; 替换为空格
        content = content.replace(/(&nbsp;|\s)+/g, ' ');

        // 去除空白字符
        content = content.trim();

        // 判断字符串是否为空
        return content.length === 0;
    }

    // 获取类型负责类型列表
    const getOfficePlatform = () => {
        let url = 'api/common/system/server/info',
            body = {
                sysId: '264'
            }
        HttpGet({
            url,
            data: body
        }).then((officePlatform) => {
            setOfficePlatform(officePlatform);
        })
    }

    const saveEquipList = () => {
        // console.log(selectEquipList,'selectEquipList');
        setChooseDeviceList(selectEquipList);
        setEquipVisible(false);
    }

    const delFile = (e, type, index) => {
        e.stopPropagation();
        e.preventDefault();
        if (type === 'img') {
            const deletedItem = imgList.splice(index, 1)[0];
            setImgList([...imgList]);
            console.log(`Deleted image: ${deletedItem}`);
        } else {
            const deletedItem = fileList.splice(index, 1)[0];
            setFileList([...fileList]);
            console.log(`Deleted file: ${deletedItem}`);
        }
    };

    // 获取敏感词
    const getSensetiveData = () => {
        HttpGet({
            url: "/api/sensitiveWord/list/word",
            data: {
                eduId: userInfo.eduId
            }
        }).then((res) => {
            console.log(res)
            // let data = res.data;
            setSensetiveData(Array.isArray(res) ? res : [])
        })
    }
    useEffect(() => {
        getSensetiveData()
    }, [])
    const showSensetive = () => {
        if (!title) {
            Taro.showToast({
                title: '请输入公告标题!',
                icon: 'none',
                duration: 2000,
            })
            return;
        }

        if (!typeItem) {
            Taro.showToast({
                title: '请选择公告类型',
                icon: 'none',
                duration: 2000,
            })
            return;
        }

        if (!depItem) {
            Taro.showToast({
                title: '请选择发布部门！',
                icon: 'none',
                duration: 2000,
            })
            return;
        }

        if (!content || isStringEmpty(content)) {
            Taro.showToast({
                title: '请输入公告内容！',
                icon: 'none',
                duration: 2000,
            })
            return;
        }
        let sensetiveWord = []
        let sensetiveEditorContent = content
        console.log(sensetiveData)
        if (sensetiveData.length > 0) {
            sensetiveData.forEach((i, index) => {
                if (content.includes(i)) {
                    sensetiveWord.push(i)
                    const regex = new RegExp(i, 'g')
                    sensetiveEditorContent = sensetiveEditorContent.replace(regex, "*")
                }
            })
        }
        console.log(sensetiveEditorContent)
        if (sensetiveWord.length > 0) {
            Dialog.show({
                content: <div>(强制发布敏感词内容会被替换为<span style={{ color: "red" }}>*</span>,并且会给管理员发送消息提醒)</div>,
                closeOnAction: true,
                title: <div>通知内容含有敏感词<span style={{ color: "red" }}>"{sensetiveWord.toString()}"</span>，确认是否发布？</div>,
                actions: [
                    [
                        {
                            key: 'confirm',
                            text: '确定',
                            // bold: true,
                        },
                        {
                            key: 'cancel',
                            text: '再想想',
                            // bold: true,
                            danger: true,
                        },
                    ],
                ],
                onAction: (action) => {
                    console.log(action)
                    if (action.key == "confirm") {
                        setContent(sensetiveEditorContent)
                        releaseNotice("release", sensetiveEditorContent)
                    }
                }
            })

        } else {
            releaseNotice("release")
        }
    }

    if (!init) {
        return <Loading />
    }

    return (
        <View className='announcement_publish'>
            <Header
                title={userVisible ? '用户选择' : equipVisible ? '设备选择' : '发布公告'}
                isLeft={true}
                isBlod={false}
                goback={goBack}
                className='header_top'
            />
            {
                preview ?
                    <View className='preview_modal'>
                        <Detail previewData={previewData} preView={preview} ></Detail>
                    </View>
                    :
                    equipVisible ?
                        <View className={'select_equip_modal ' + (Utils.getSystemInfo() === 'weapp' ? 'is_weapp' : '')}>
                            <View className={'equip_name'} onClick={() => handlePopLayer('open', 'build')}><View className={'equip_icon ' + (showBuildList ? 'equip_icon_open' : '')}></View>楼牌</View>
                            <View className='equip_view'>
                                {showBuildList ? useGetIsMapArray(buildList) ?
                                    buildList.map((item, index) => {
                                        let isObjectInArray = selectEquipList.some(obj => obj.buildingBoardId === item.buildingBoardId)

                                        return (
                                            <View className='equip_item'>
                                                <LgCheckbox className='check_box' type='B' key={isObjectInArray} default={isObjectInArray ? 1 : 0} onClick={() => changeCheckedEquip(item)}>{item.buildingBoardName}</LgCheckbox>
                                            </View>
                                        )
                                    })
                                    : <View className='empty_container'>
                                        <LgEmptyContent type='B' text={'暂无楼牌'} />
                                    </View>
                                    : ''}
                            </View>
                            <View className='equip_name' onClick={() => handlePopLayer('open', 'class')}><View className={'equip_icon ' + (showClassList ? 'equip_icon_open' : '')}></View>班牌</View>
                            <View className='equip_view'>
                                {showClassList ? useGetIsMapArray(classList) ?
                                    classList.map((item, index) => {
                                        let isObjectInArray = selectEquipList.some(obj => obj.boardId === item.boardId)
                                        return (
                                            <View className='equip_item'>
                                                <LgCheckbox className='check_box' type='B' key={isObjectInArray} default={isObjectInArray ? 1 : 0} onClick={() => changeCheckedEquip(item)}>{item.boardName}</LgCheckbox>
                                            </View>
                                        )
                                    })
                                    : <View className='empty_container'>
                                        <LgEmptyContent type='B' text={'暂无班牌'} />
                                    </View>
                                    : ''}
                            </View>
                            <View className='equip_name' onClick={() => handlePopLayer('open', 'board')}><View className={'equip_icon ' + (showBoardList ? 'equip_icon_open' : '')}></View>广播终端</View>
                            <View className='equip_view'>
                                {showBoardList ? useGetIsMapArray(boardList) ?
                                    boardList.map((item, index) => {
                                        let isObjectInArray = selectEquipList.some(obj => obj.buildingId === item.buildingId)
                                        return (
                                            <View className='equip_item'>
                                                <LgCheckbox className='check_box' type='B' key={isObjectInArray} default={isObjectInArray ? 1 : 0} onClick={() => changeCheckedEquip(item)}>{item.buildingName + '-' + item?.devices[0].deviceName}</LgCheckbox>
                                            </View>
                                        )
                                    })
                                    : <View className='empty_container'>
                                        <LgEmptyContent type='B' text={'暂无广播终端'} />
                                    </View>
                                    : ''}
                            </View>
                            <View className='save_btn'>
                                <LgButton width={200} height={88} className="btn" type='B' onClick={() => saveEquipList()}>确定</LgButton>
                            </View>
                        </View>
                        :
                        userVisible ?
                            <View className={'select_user_modal ' + (Utils.getSystemInfo() === 'weapp' ? 'is_weapp' : '')}>
                                <LancooSelect
                                    token={token}
                                    officeUrl={officePlatform.webSvrAddr}
                                    selectUserList={selectUserList}
                                    allSelectObj={allSelectObj}
                                    onConfirm={confirm} />
                            </View> :
                            <><View className='publish_container'>
                                <View className='publish_header'>
                                    <View className='title'>
                                        <LgInput
                                            value={title}
                                            maxLength={30}
                                            type="A"
                                            isNeed={true}
                                            inputName={'标题'}
                                            // title={<Text><Text className='must-fill'>*</Text>类型</Text>}
                                            placeholder="请输入"
                                            onChange={value => setTitle(value)}
                                        ></LgInput>
                                        <View className='horizontal_line'></View>
                                        <LgCell
                                            title="类型"
                                            content={typeItem ? typeItem.typeName : '请选择公告类型'}
                                            showIcon={true}
                                            onClick={() => {
                                                handlePopLayer('open', 'type')
                                            }}
                                            type='A'
                                        ></LgCell>
                                        <LgPopLayer
                                            position="bottom"
                                            confirm={() => { handlePopLayer('close', 'type') }}
                                            showLayer={() => handlePopLayer('close', 'type')}
                                            title={'公告类型'}
                                            showClose
                                            isOpen={typeVisible}>
                                            {myTypeList.map((item, index) => {
                                                return (
                                                    <View className="kind_one" key={index} onClick={() => changeObj(item, 'type')}>{item.typeName}</View>
                                                )
                                            })}
                                        </LgPopLayer>
                                        <View className='horizontal_line'></View>
                                        <View className='viewable_object'>
                                            <View className='check_obj_span'>可查看对象</View>
                                            <View className='check_obj'>
                                                {canViewList.map((item, index) => {
                                                    return (
                                                        <View className='check_box_div'>
                                                            <LgCheckbox className='check_box' type='B' default={1} onClick={() => changeChecked(index)}>{item.label}</LgCheckbox>
                                                        </View>
                                                    )
                                                })}
                                                {canViewList.length == 0 ?
                                                    <Text className='no_check_obj'>请先选择公告类型</Text>
                                                    : ''}
                                            </View>
                                        </View>
                                        <View className='horizontal_line'></View>
                                        <LgCell
                                            title={<Text><Text className='must-fill'>*</Text>发布部门</Text>}
                                            content={depItem ? depItem.departmentName : '请选择发布部门'}
                                            showIcon={true}
                                            onClick={() => {
                                                handlePopLayer('open', 'dep')
                                            }}
                                            type='A'
                                        ></LgCell>
                                        <LgPopLayer
                                            position="bottom"
                                            confirm={() => { handlePopLayer('close', 'dep') }}
                                            showLayer={() => handlePopLayer('close', 'dep')}
                                            title={'部门选择'}
                                            showClose
                                            isOpen={depVisible}>
                                            {depList?.map((item, index) => {
                                                return (
                                                    <View className="kind_one" key={index} onClick={() => changeObj(item, 'dep')}>{item.departmentName}</View>
                                                )
                                            })}
                                        </LgPopLayer>
                                        <View className='horizontal_line horizontal_line_margin'></View>
                                        <MyEditor id='editor' getHtmlContent={(html) => { setContent(html && html !== '<p><br></p>' ? html : '') }} value={content} />
                                    </View>
                                </View>
                                <View className='file_container'>
                                    <View className='file_container_top'>
                                        <Text className='file_text'>附件{imgList.length + fileList.length > 0 ?
                                            <Text className='file_num'>({imgList.length + fileList.length}个附件)</Text>
                                            : ''}</Text>
                                        <View className='file_container_icon' onClick={() => { Utils.chooseFile1({ count: 1, success: uploadSuccess, fail: uploadFail, }) }}><Text className='addIcon'></Text></View>
                                    </View>
                                    {useGetIsMapArray(imgList) ?
                                        <View className='image_box'>
                                            {/* <View className="imgBox"> */}
                                            {useGetIsMapArray(imgList) && imgList.map((item: any, index) => {
                                                return (
                                                    <View key={index} className="imgItem_publish" onClick={() => showPreView(item)}>
                                                        <Image className="imgSrc_publish" src={item.url} mode='aspectFill' />
                                                        <View className='del_icon' onClick={(e) => delFile(e, 'img', index)}></View>
                                                    </View>
                                                )
                                            })}
                                            {/* </View> */}
                                        </View>
                                        : ''}
                                    <View className='file_box_list'>
                                        {fileList.map((item: any, index) => {
                                            let icon = Utils.getFileType(decodeURIComponent(item.fileName))
                                            let fileIcon = {
                                                "img": "0a00901",
                                                "doc": "0a00101",
                                                "ppt": "0a00201",
                                                "pdf": "0a00501",
                                                "txt": "0a00401",
                                                "xls": "0a00301",
                                                "music": "0a00601",
                                                "video": "0a00701",
                                                "html": "0a01001",
                                                "zip": "0a01201",
                                                "otr": "0a01101"
                                            }
                                            let src = fileObj[fileIcon[icon]]
                                            let size = Utils.getFileSize(item.size)
                                            return (
                                                <View className='file_item'>
                                                    <View className='file_icon' style={{ backgroundImage: `url(${src})` }}></View>
                                                    <View className='file_info'>
                                                        <View className='file_name'>{item.fileName}</View>
                                                        <View className='file_size'>{size}</View>
                                                    </View>
                                                    <View className='del_icon' onClick={(e) => delFile(e, 'file', index)}></View>
                                                </View>
                                            )
                                        })}
                                    </View>
                                </View>
                                <View className='advanced_function' style={advancedVisible ? {} : { borderBottom: '10px solid #f5f5f5' }}>
                                    <View className='advanced_function_btn' onClick={() => handlePopLayer('open', 'advanced')}>
                                        <Text>高级功能</Text>
                                        <View className={'advanced_icon ' + (advancedVisible ? 'advanced_icon_open' : '')}></View>
                                    </View>
                                    {advancedVisible ?
                                        <View className='advanced_function_setting'>
                                            <View className='is_top'>
                                                <Text className='to_top'>是否置顶</Text>
                                                <View className='is_top_switch'><LgSwitch default={isTop} onClick={() => setTop()} /></View>
                                            </View>
                                            <View className='horizontal_line'></View>
                                            {/* <LgCell
                                                className='select_equipment'
                                                title="选择设备"
                                                content={chooseDeviceList.length > 0 ? <View className='select_user_num'>已选<Text className='user_num_text'>{chooseDeviceList.length}</Text>个设备</View> : '选择设备'}
                                                showIcon={true}
                                                onClick={() => {
                                                    handlePopLayer('open', 'equip')
                                                }}
                                                type='A'
                                            ></LgCell>
                                            <View className='horizontal_line'></View> */}
                                            <LgCell
                                                className='select_user'
                                                title="提醒对象"
                                                content={selectUserList.length > 0 ? <View className='select_user_num'>已选<Text className='user_num_text'>{selectUserList.length}</Text>个对象</View> : '提醒对象'}
                                                showIcon={true}
                                                onClick={() => {
                                                    handlePopLayer('open', 'user')
                                                }}
                                                type='A'
                                            ></LgCell>
                                        </View>
                                        : ''}
                                </View>
                            </View><View className='footer_option'>
                                    <LgButton width={200} height={88} className="btn" type='D' onClick={() => releaseNotice('preview')}>预览</LgButton>
                                    <LgButton width={200} height={88} className="btn" type='B' onClick={() => releaseNotice('save')}>保存</LgButton>
                                    <LgButton width={200} height={88} className="btn" type='B' color='open' onClick={() => showSensetive()}>发布</LgButton>
                                </View></>
            }
            {/* {footerOption} */}
            <PopoverDownload
                visible={visible}
                setVisible={setVisible}
                file={currentFile}
                index={currentIndex}
                download={download}
            />
        </View>
    )
}

export default App